#数据库连接工具类
import logging

import pymysql
class DBUtil(object):

    conn = None
    @classmethod
    def __get_conn(cls):
        if cls.conn is None :
            cls.conn = pymysql.connect(
                host="192.168.101.33",port=3306,user="root",
                       database="tpshop2.0",password="123456",charset="utf8")

        return cls.conn
    @classmethod
    def __close_conn(cls):
        if cls.conn is not None:
            cls.conn.close()
            cls.conn = None

    # 查询一条数据常用方法
    @classmethod
    def select_one(cls,sql):
        try:
            cls.conn = cls.__get_conn()
            cursor = cls.conn.cursor()
            cursor.execute(sql)
            res = cursor.fetchone()
        except Exception as e:
            logging.error("sql查询语句出错：",str(e))
        finally:
            cursor.close()
            cls.__close_conn()
            return res


    # 增删改常用方法
    @classmethod
    def uid_db(cls,sql):
        try:
            cls.conn = cls.__get_conn()
            cursor = cls.conn.cursor()
            cursor.execute(sql)
            logging.info("影响行数：",cls.conn.affected_rows())
            cls.conn.commit()

        except Exception as e:
            logging.error("sql修改语句出错：", str(e))
            cls.conn.rollback()
        finally:
            cursor.close()
            cls.__close_conn()

if __name__ == "__main__":
    res = DBUtil.select_one("select * from tp_ad;");
    print(res)
    DBUtil.uid_db("DELETE  from tp_spec WHERE id = 31; ")

